package com.goodmr.passport.config;

import com.goodmr.passport.config.property.DataSourceProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

/**
 * 数据库配置
 *
 * @author <a href="mailto:bingdong13@msn.com">bigo</a>
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "accountEntityManagerFactory",
        transactionManagerRef = "accountTransactionManager",
        basePackages = {"com.goodmr.passport"}
)
public class DataSourceConfig {

    private final DataSourceProperty dataSourceProperty;

    @Autowired
    public DataSourceConfig(DataSourceProperty dataSourceProperty) {
        this.dataSourceProperty = dataSourceProperty;
    }

    @Bean(name = "accountDataSource")
    public DataSource dataSource() {
        return DataSourceBuilder.create()
                .url(dataSourceProperty.getUrl())
                .username(dataSourceProperty.getUsername())
                .password(dataSourceProperty.getPassword())
                .driverClassName(dataSourceProperty.getDriverClassName())
                .build();
    }

    @Bean(name = "accountEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dataSource())
                .packages("com.goodmr.passport")
                .persistenceUnit("PassportAccount")
                .build();
    }

    @Bean("accountTransactionManager")
    public PlatformTransactionManager transactionManagerReport(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactory(builder).getObject());
    }

    @Bean(name = "accountEntityManager")
    public EntityManager entityManagerReport(EntityManagerFactoryBuilder builder) {
        return entityManagerFactory(builder).getObject().createEntityManager();
    }
}
